import { Injectable } from '@angular/core'
import { Http, Headers, RequestOptions, Response } from '@angular/http'
import { Cookie } from 'ng2-cookies'
import { AUTH_COOKIE_NAME, DEFAULT_ICONS } from './consts'
import { Observable } from 'rxjs/Observable'

@Injectable()
export class Functions {

  getRequestOptions (): RequestOptions {
    const token = Cookie.get(AUTH_COOKIE_NAME)
    const headers = new Headers({ Authorization: `Bearer ${token}` })
    const options = new RequestOptions({ headers })
    return options
  }

  isDefaultIcon (icon): boolean {
    return DEFAULT_ICONS.includes(icon)
  }

  parseData (res: Response) {
    return res.json() || []
  }

  handleHttpError (error: Response | any) {
    // This returns another Observable for the observer to subscribe to
    if (error._body) {
      const err = error.json()
      return err
    }
    const msg = error.message ? error.message : error.toString()
    return { msg }
  }
}
